<template>
  <div class="wu-upload">
    <el-upload
      class="upload-style"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="handleUploadSuccess"
      :before-upload="beforeUpload"
    >
      <img v-if="urlProp" :src="urlProp" class="avatar" />
      <el-icon v-else class="upload-style-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import { UploadProps } from 'element-plus'
/*上传模块--暂支持一张图片 */
defineProps<{
  uploadUrl: string
  urlProp: string
}>()
const emits = defineEmits(['update:urlProp', 'onsuccess'])
// const previewUrl = ref('')
// 上传前钩子
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('Upload picture must be image format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Upload picture size can not exceed 2MB!')
    return false
  }
  return true
}
// 上传成功钩子
const handleUploadSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //   previewUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log('response', response)
  emits('update:urlProp', response.data)
  // form校验此项
  emits('onsuccess', response.data)
}
</script>

<style lang="scss" scoped>
// upload style
.upload-style .avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>

<style>
.upload-style .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.upload-style .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.upload-style-icon {
  width: 130px;
  height: 130px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
